from ccpm.pmbase import PluginBase, PmUtil
from ccpm.glan import Lan
import os
from ccpm.constants import Constant
import sys
import shutil
from ccpm.net import NetUtil
from ccpm.model.modelusr import ModelUsr


def fmt_verstr(verstr):
    nums = verstr[1:].split(".")
    return int(nums[0]) * 100 + int(nums[1]) * 10 + int(nums[2])


class UnPublishPlugin(PluginBase):

    PLUGIN_INFO = dict(
        name="unpublish",
        help="unpublish remote ccpm plugin!"
    )

    def __init__(self):
        if not hasattr(self, "_inc"):
            self._inc = super().__init__(self.PLUGIN_INFO)
        return self._inc

    def parser_config(self, argparser):
        super().parser_config(argparser)
        argparser.add_argument("ptar",
                               help="the plugin name to unpublish like mail@v1.0.0")

    def run(self, argpars):
        super().run(argpars)
        if not PmUtil.chk_usr_enable():
            self.logger.error(
                Lan.p(self.name, "ERR_CHK_USER"))
            return

        pluginname = argpars.ptar
        if PmUtil.is_namever_be_content(pluginname):
            ilist = pluginname.split("@")
            pname, pver = ilist[0], ilist[1]
            # todo usrtype
            ret = NetUtil.dele_plugin_db(
                1, ModelUsr().get_name(), pname, pver)
            if ret:
                self.logger.info(
                    Lan.p(self.name, "DESC_DELETE_SUC", pluginname))
            else:
                self.logger.info(
                    Lan.p(self.name, "ERR_DELETE_FAILED", pluginname))
        else:
            self.logger.error(
                Lan.p(self.name, "ERR_DELETE_FAILED", pluginname))


__all__ = [
    "UnPublishPlugin"
]
